package com.chen.back.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chen.back.common.dto.PermissionDto;
import com.chen.back.entity.Permission;
import com.chen.back.mapper.PermissionMapper;
import com.chen.back.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chen
 * @since 2022-02-24
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {


    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public Set<String> getAllPermissionByUsername(String username) {
        return permissionMapper.selectAllPermissionCodeByUsername(username);
    }

    @Override
    public List<Permission> tree() {
        // 获取所有菜单信息
        List<Permission> sysMenus = this.list(new QueryWrapper<Permission>().orderByAsc("permission_id"));

        // 转成树状结构
        return buildTreeMenu(sysMenus);
    }
    private List<Permission> buildTreeMenu(List<Permission> menus) {

        List<Permission> finalMenus = new ArrayList<>();

        // 先各自寻找到各自的孩子
        for (Permission menu : menus) {

            for (Permission e : menus) {
                if (menu.getPermissionId() == e.getFatherId()) {
                    menu.getChildren().add(e);
                }
            }

            // 提取出父节点
            if (menu.getFatherId() == 0) {
                finalMenus.add(menu);
            }
        }

        System.out.println(JSONUtil.toJsonStr(finalMenus));
        return finalMenus;
    }

    private List<PermissionDto> convert(List<Permission> menuTree) {
        List<PermissionDto> menuDtos = new ArrayList<>();

        menuTree.forEach(m -> {
            PermissionDto dto = new PermissionDto();

            dto.setId(m.getPermissionId());
            dto.setPermissionCode(m.getPermissionCode());
            dto.setPermissionName(m.getPermissionName());
//            dto.setComponent(m.getComponent());
            dto.setPath(m.getPath());

            if (m.getChildren().size() > 0) {

                // 子节点调用当前方法进行再次转换
                dto.setChildren(convert(m.getChildren()));
            }

            menuDtos.add(dto);
        });

        return menuDtos;
    }

}
